<script setup lang="ts">


import {ref} from "vue";
import {
  Category,
  deleteCategory,
  getAllCategory,
  getEmptyCategory,
  saveOrUpdateCategory
} from "@/net/controller/category-controller.ts";
import {showSimpleDialog} from "@/utils/dialog-utils.ts";

const cats = ref<Category[]>([])

async function refreshCats() {
  cats.value = await getAllCategory()
}

refreshCats()

const showEditorDialog = ref(false)
const editorDialogData = ref<Category>(getEmptyCategory())

function openEditorDialog(category: Category) {
  showEditorDialog.value = true
  editorDialogData.value = category
}

function onEditorDialogSaveConfirmed() {
  saveOrUpdateCategory(editorDialogData.value).then(() => {
    ElMessage.success("保存成功")
    showEditorDialog.value = false
    refreshCats()
  })
}

function onDelete(category: Category) {
  showSimpleDialog(`删除 ${category.name}`, `是否要删除分类 ${category.name}, 若该分类存在文章将会删除失败`, () => {
    deleteCategory(category.categoryId).then(() => {
      ElMessage.success("删除成功")
      refreshCats()
    })
  })
}
</script>

<template>
  <main>
    <div>
      <el-button size="default" type="info" @click="refreshCats()">刷新</el-button>
      <el-button size="default" type="primary" @click="openEditorDialog(getEmptyCategory())">添加</el-button>
    </div>

    <el-table :data="cats" style="width: 100%; margin-top: 1rem">
      <el-table-column fixed prop="categoryId" label="分类ID" width="120" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="permission" label="权限" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openEditorDialog(scope.row)">
            编辑
          </el-button>
          <el-button link type="danger" size="small" @click="onDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="showEditorDialog" title="添加/编辑分类" width="600">
      <el-form size="default" :model="editorDialogData" label-width="auto" style="max-width: 600px" label-position="top">
        <el-form-item label="名称">
          <el-input v-model="editorDialogData.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editorDialogData.description" />
        </el-form-item>
        <el-form-item label="权限">
          <el-input v-model="editorDialogData.permission" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div>
          <el-button size="default" @click="showEditorDialog = false">取消</el-button>
          <el-button size="default" type="primary" @click="onEditorDialogSaveConfirmed()">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </main>
</template>

<style scoped>

</style>